<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item :label="$t('user_userName')" prop="username">
        <el-input
          v-model="queryParams.username"
          :placeholder="$t('inputUserName')"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('user_name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('inputName')"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('userEmail')" prop="email">
        <el-input
          v-model="queryParams.email"
          :placeholder="$t('inputUserEmail')"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t('search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t('reset')
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-auth="['CREATE']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t('addBtn') }}</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="userList" border @sort-change="sortChange">
      <el-table-column
        :label="$t('user_userName')"
        sortable
        prop="username"
        width="150"
      />
      <el-table-column
        :label="$t('user_name')"
        prop="name"
        sortable
        :show-overflow-tooltip="true"
        min-width="150"
      />
      <el-table-column
        :label="$t('userEmail')"
        prop="email"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        :label="$t('userRoleDesc')"
        prop="role_desc"
        :show-overflow-tooltip="true"
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="$t('userIsActive')"
        prop="is_active"
        width="120"
      >
        <template slot-scope="scope">
          <DataStatus :status="scope.row.is_active" />
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('userValidDate')"
        prop="valid_date"
        :show-overflow-tooltip="true"
        min-width="110"
      />
      <el-table-column
        :label="$t('userInvalidDate')"
        prop="invalid_date"
        :show-overflow-tooltip="true"
        min-width="110"
      />
      <el-table-column
        :label="$t('operate')"
        align="center"
        width="250"
        fixed="right"
        class-name="fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >{{ $t('detailBtn') }}</el-button>
          <el-button
            v-auth="['UPDATE']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t('modifyBtn') }}</el-button>
          <el-dropdown
            v-more
            size="mini"
            trigger="click"
            @command="command => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right" />{{ $t('moreBtn') }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-auth="['AUTHORIZE']"
                command="handleAuthorize"
                icon="el-icon-connection"
              >{{ $t("dataAccessAuthorizeBtn") }}</el-dropdown-item>
              <el-dropdown-item
                v-auth="['RESET']"
                command="handleResetPassword"
                icon="el-icon-key"
              >{{ $t('resetPwdBtn') }}</el-dropdown-item>
              <el-dropdown-item
                v-auth="['DELETE']"
                command="handleDeleteUser"
                icon="el-icon-delete"
              >{{ $t('deleteBtn') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <UserSheet ref="userSheet" @refreshList="getList" />
    <UserInquire ref="userInquire" />
    <UserSensitiveFieldAuthorize ref="sensitiveFieldAuthorize" />
  </div>
</template>

<script>
import store from '@/store';
import { mapGetters } from 'vuex';
import { deleteUserApi, resetPasswordApi } from '@/views/rbac/api/rbac.api';
import UserInquire from '@/views/rbac/components/UserInquire';
import UserSheet from '@/views/rbac/components/UserSheet';
import UserSensitiveFieldAuthorize from './UserSensitiveFieldAuthorize';

export default {
  name: 'User',
  components: {
    UserInquire,
    UserSheet,
    UserSensitiveFieldAuthorize
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        username: undefined,
        name: undefined,
        email: undefined,
        ordering: undefined
      },
      // 操作权限控制
      permissions: []
      // operateMore: false
    };
  },
  computed: {
    ...mapGetters(['userList'])
  },
  created() {
    // this.handleRbac();
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    async getList() {
      // 操作权限控制
      this.permissions = this.handleMenuPermission(this)
      this.loading = true;
      var resp = await store.dispatch('rbac/getUserList', this.queryParams);
      if (resp.success) {
        this.total = resp.data.count;
        this.loading = false;
      } else {
        this.targaMessageBox(this, resp.msg);
        this.loading = false;
      }
    },
    // handleRbac() {
    //   this.permissions = this.handleMenuPermission(this);
    //   if (this.permissions.includes('DELETE') || this.permissions.includes('RESET') || this.permissions.includes('AUTHORIZE')) {
    //     this.operateMore = true;
    //   }
    // },
    sortChange({ prop, order }) {
      var ordering;
      if (order === 'ascending') {
        ordering = '' + prop;
      } else if (order === 'descending') {
        ordering = '-' + prop;
      } else {
        ordering = undefined;
      }
      this.queryParams.ordering = ordering;

      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleDeleteUser':
          this.handleDelete(row);
          break;
        case 'handleResetPassword':
          this.handleResetPassword(row)
          break;
        case 'handleAuthorize':
          this.handleMenuSensitiveFieldAuthorize(row)
          break;
        default:
          break;
      }
    },
    handleMenuSensitiveFieldAuthorize(row) {
      this.$refs.sensitiveFieldAuthorize.openSheetDialog(row.id);
    },
    handleUpdate(row) {
      this.$refs.userSheet.openSheetDialog(this.handleObjectCopy(row));
    },
    handleDetail(row) {
      this.$refs.userInquire.openSheetDialog(row);
    },
    handleAdd() {
      this.$refs.userSheet.openSheetDialog(undefined);
    },
    async handleResetPassword(row) {
      this.$confirm(
        this.$t('resetPasswordConfirm', {
          title: this.$t('user_userName'),
          value: row.username
        }),
        this.$t('warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'), cancelButtonClass: 'btn-cancel-to-right',
          type: 'warning'
        }
      ).then(async() => {
        var data = { 'user': row.id }
        var resp = await resetPasswordApi(data)
        if (resp.success) {
          this.targaMessage(
            this.$t('resetPasswordSuccess', {
              title: this.$t('user_userName'),
              value: row.username
            })
          );
        } else {
          this.targaMessageBox(this, resp.msg);
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        this.$t('dataDeleteConfirm', {
          title: this.$t('user_userName'),
          value: row.username
        }),
        this.$t('warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'), cancelButtonClass: 'btn-cancel-to-right',
          type: 'warning'
        }
      ).then(async() => {
        var resp = await deleteUserApi(row.id);
        if (resp.success) {
          this.targaMessage(
            this.$t('deleteSuccess', {
              title: this.$t('user_userName'),
              value: row.username
            })
          );
          this.getList();
        } else {
          this.targaMessageBox(this, resp.msg);
        }
      });
    }
  }
};
</script>
